package com.daikun.common.utils;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import com.daikun.common.enums.BaseResultEnum;
import com.daikun.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.util.HashMap;
import java.util.Map;

/**
 * 发送飞书消息
 * @author earl created 2025-07-16
 * @version init 0.0.1
 */
@Slf4j
public class FeiShuUtil {

    /**
     * 发送飞书消息 ~ 会将消息发送到 ownerShip 对应的业务告警群中
     * @param msg 消息内容
     * @param ownerShip 当前 app 唯一标识
     */
    public static void send(String msg, String ownerShip) {
        send(msg, ownerShip, null);
    }

    /**
     * 发送飞书消息 ~ 会将消息发送到 topic 指定的群中
     * @param msg 消息内容
     * @param ownerShip app 唯一标识
     * @param topic t_sys_talk_config 表中进行配置
     */
    public static void send(String msg, String ownerShip, String topic) {
        String isTest = StrUtil.blankToDefault(SpringUtil.getProperty("sys.param.isDingdingTest"), "true");
        try {
            if (StrUtil.isBlank(msg) ||  StrUtil.isBlank(ownerShip)) {
                throw new BizException(BaseResultEnum.PARAM_FAIL);
            }
            topic = StrUtil.isBlank(topic) ? "SAAS_" + ownerShip.toUpperCase() + "_DINGTALK_CODE" : topic;
            Map<String, Object> paramMap = MapUtil.builder(new HashMap<String, Object>())
                    .put("talkPassWay", topic).put("message", msg)
                    .put("title", SpringUtil.getProperty("spring.application.name")).put("atMobiles", "18272864246")
                    .put("bizId", StrUtil.blankToDefault(MDC.get("traceId"), IdUtil.simpleUUID())).put("isTest", isTest).build();
            HttpUtil.post(SpringUtil.getProperty("dingtalk.url"), paramMap, Integer.parseInt(StrUtil.blankToDefault(SpringUtil.getProperty("inner.rest.outTime"), "3000")));
        } catch (Exception e) {
            log.info("FeiShu 消息发送失败 -> msg = {}, isTest = {}, ownerShip = {}, topic = {}", msg, isTest, ownerShip, topic, e);
        }
    }

}
